package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.DateUtils;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.http.UrlUtils;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectExcellent;
import com.ecnu.system.domain.ProjectTeacher;
import com.ecnu.system.domain.dto.ExcellentDTO;
import com.ecnu.system.domain.dto.ProjectListDTO;
import com.ecnu.system.domain.vo.ExcellentVO;
import com.ecnu.system.domain.vo.ProjectListVO;
import com.ecnu.system.mapper.ProjectExcellentMapper;
import com.ecnu.system.mapper.ProjectMapper;
import com.ecnu.system.mapper.ProjectResultMapper;
import com.ecnu.system.mapper.ProjectTeacherMapper;
import com.ecnu.system.service.IProjectExcellentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ecnu.common.utils.OtherUtil.extractFirstHtml;
import static com.ecnu.system.domain.menu.OtherMenu.sysUrl;

/**
 * <p>
 * ecnu_活动表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-19
 */
@Service
public class ProjectExcellentServiceImpl extends ServiceImpl<ProjectExcellentMapper, ProjectExcellent> implements IProjectExcellentService {

    @Autowired
    private ProjectExcellentMapper excellentMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectResultMapper resultMapper;
    @Autowired
    private ProjectTeacherMapper projectTeacherMapper;


    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    @Override
    public void del(String resultId) {
//        QueryWrapper<ProjectExcellent> wrapper = new QueryWrapper<>();
//        wrapper.eq("result_id", resultId);
        LambdaQueryWrapper<ProjectExcellent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectExcellent::getResultId, resultId);
        int delete = excellentMapper.delete(wrapper);
        System.out.println("delete = " + delete);
    }

    @Override
    public TableDataInfo projectList(ExcellentDTO dto, LoginUser loginUser) {
        Project project = projectMapper.selectOne(new QueryWrapper<Project>()
                .eq("id", dto.getProjectId())
                .eq("del_flag", "0"));
        if (project == null) {
            return OtherUtil.tableError("活动不存在或已被删除，请联系管理员");
        }
        startPage(dto.getPageDomain());
        List<ExcellentVO> excellentVOS = excellentMapper.selectListByProId(dto);
        excellentVOS.forEach(excellentVO -> {
            excellentVO.setCreateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, excellentVO.getDate()));
            excellentVO.setRealName(excellentVO.getCreateUser());
            excellentVO.setFullurl(UrlUtils.getUrl() + excellentVO.getUrl());
        });
        return OtherUtil.tableSuccess(excellentVOS);
    }

    @Override
    public TableDataInfo list(ProjectListDTO dto) {
        try {
            //先取成果，按照活动分组
            //在对活动中成果数量排序
            startPage(dto.getPageDomain());
            List<ProjectListVO> listVOPage = resultMapper.getListForExcellent(dto);
            if (listVOPage.isEmpty()) {
                return OtherUtil.tableSuccess(listVOPage);
            }
            List<String> projectIds = listVOPage.stream()
                    .map(ProjectListVO::getId)
                    .collect(Collectors.toList());

            // 批量查询所有项目的负责人
            QueryWrapper<ProjectTeacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("pro_id", projectIds); // 使用 in 查询
            List<ProjectTeacher> projectTeachers = projectTeacherMapper.selectList(queryWrapper);

            // 将负责人按项目 id 分组
            Map<String, List<ProjectTeacher>> projectTeachersMap = projectTeachers.stream()
                    .collect(Collectors.groupingBy(ProjectTeacher::getProId));
            // 为每个项目设置负责人
            listVOPage.forEach(projectListVO -> {
                List<ProjectTeacher> teachers = projectTeachersMap.get(projectListVO.getId());
                String userVOs = teachers != null ?
                        teachers.stream()
                                .map(ProjectTeacher::getTeachName) // 提取 teachName
                                .collect(Collectors.joining(", ")) : // 用逗号拼接
                        "";
                projectListVO.setTeacher(userVOs);
                projectListVO.setTitle(extractFirstHtml(projectListVO.getTitle()));
            });
            return OtherUtil.tableSuccess(listVOPage);
        } catch (Exception e) {
            return OtherUtil.tableError(e.getMessage());
        }
    }

    @Override
    public TableDataInfo homeList(String proType) {
        PageDomain domain = new PageDomain();
        domain.setPageNum(1);
        domain.setPageSize(4);
        ProjectListDTO dto = new ProjectListDTO();
        dto.setProType(proType);
        dto.setPageDomain(domain);
        return this.list(dto);
    }
}
